<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <title>互斥量 - 欢迎来到SY的博客</title><meta name="description" content="互斥量"><meta property="og:title" content="互斥量" />
<meta property="og:description" content="互斥量" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://acking-you.gitee.io/posts/%C3%A4%C2%BA%C3%A6%C3%A9/" /><meta property="og:image" content="https://acking-you.gitee.io/logo.png"/><meta property="article:section" content="posts" />
<meta property="article:published_time" content="2022-08-23T00:00:00+00:00" />
<meta property="article:modified_time" content="2022-08-23T00:00:00+00:00" />

<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:image" content="https://acking-you.gitee.io/logo.png"/>

<meta name="twitter:title" content="互斥量"/>
<meta name="twitter:description" content="互斥量"/>
<meta name="application-name" content="FeelIt">
<meta name="apple-mobile-web-app-title" content="FeelIt"><meta name="theme-color" content="#ffffff"><meta name="msapplication-TileColor" content="#da532c"><link rel="canonical" href="https://acking-you.gitee.io/posts/%C3%A4%C2%BA%C3%A6%C3%A9/" /><link rel="prev" href="https://acking-you.gitee.io/posts/%C3%A5%C3%A7%C2%BA%C3%A7%C3%A5%C3%A6api%C3%A8%C3%A8/" /><link rel="next" href="https://acking-you.gitee.io/posts/%C3%A6%C3%A4%C3%A5%C3%A9/" /><link rel="stylesheet" href="/css/page.min.css"><link rel="stylesheet" href="/css/home.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "互斥量",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/acking-you.gitee.io\/posts\/%C3%A4%C2%BA%C3%A6%C3%A9\/"
        },"genre": "posts","keywords": "互斥量","wordcount":  4845 ,
        "url": "https:\/\/acking-you.gitee.io\/posts\/%C3%A4%C2%BA%C3%A6%C3%A9\/","datePublished": "2022-08-23T00:00:00+00:00","dateModified": "2022-08-23T00:00:00+00:00","publisher": {
            "@type": "Organization",
            "name": "作者"},"author": {
                "@type": "Person",
                "name": "作者"
            },"description": "互斥量"
    }
    </script></head><body data-header-desktop="auto" data-header-mobile="auto"><script>(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('auto' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : 'auto' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><header class="desktop" id="header-desktop">
    <div class="header-wrapper">
        <div class="header-title">
            <a href="/" title="欢迎来到SY的博客">欢迎来到SY的博客</a>
        </div>
        <div class="menu">
            <div class="menu-inner"><a class="menu-item" href="/posts/"> 文章 </a><a class="menu-item" href="/tags/"> 标签 </a><a class="menu-item" href="/categories/"> 分类 </a><span class="menu-item delimiter"></span><span class="menu-item search" id="search-desktop">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-desktop">
                        <a href="#" class="search-button search-toggle" id="search-toggle-desktop" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="#" class="search-button search-clear" id="search-clear-desktop" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-desktop">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </span><a href="javascript:void(0);" class="menu-item theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div>
        </div>
    </div>
</header><header class="mobile" id="header-mobile">
    <div class="header-container">
        <div class="header-wrapper">
            <div class="header-title">
                <a href="/" title="欢迎来到SY的博客">欢迎来到SY的博客</a>
            </div>
            <div class="menu-toggle" id="menu-toggle-mobile">
                <span></span><span></span><span></span>
            </div>
        </div>
        <div class="menu" id="menu-mobile"><div class="search-wrapper">
                    <div class="search mobile" id="search-mobile">
                        <input type="text" placeholder="搜索文章标题或内容..." id="search-input-mobile">
                        <a href="#" class="search-button search-toggle" id="search-toggle-mobile" title="搜索">
                            <i class="fas fa-search fa-fw"></i>
                        </a>
                        <a href="#" class="search-button search-clear" id="search-clear-mobile" title="清空">
                            <i class="fas fa-times-circle fa-fw"></i>
                        </a>
                        <span class="search-button search-loading" id="search-loading-mobile">
                            <i class="fas fa-spinner fa-fw fa-spin"></i>
                        </span>
                    </div>
                    <a href="#" class="search-cancel" id="search-cancel-mobile">
                        取消
                    </a>
                </div><a class="menu-item" href="/posts/" title="">文章</a><a class="menu-item" href="/tags/" title="">标签</a><a class="menu-item" href="/categories/" title="">分类</a><div class="menu-item"><a href="javascript:void(0);" class="theme-switch" title="切换主题">
                    <i class="fas fa-adjust fa-fw"></i>
                </a>
            </div></div>
    </div>
</header><div class="search-dropdown desktop">
    <div id="search-dropdown-desktop"></div>
</div>
<div class="search-dropdown mobile">
    <div id="search-dropdown-mobile"></div>
</div><main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">目录</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single" data-toc="disable"><div class="featured-image"><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://w.wallhaven.cc/full/dp/wallhaven-dplz6l.jpg"
        data-srcset="https://w.wallhaven.cc/full/dp/wallhaven-dplz6l.jpg, https://w.wallhaven.cc/full/dp/wallhaven-dplz6l.jpg 1.5x, https://w.wallhaven.cc/full/dp/wallhaven-dplz6l.jpg 2x"
        data-sizes="auto"
        alt="https://w.wallhaven.cc/full/dp/wallhaven-dplz6l.jpg"
        title="互斥量" /></div><div class="single-card" data-image="true"><h2 class="single-title animated flipInX">互斥量</h2><div class="post-meta">
                <div class="post-meta-line"><span class="post-author"><a href="/" title="Author" rel=" author" class="author"><i class="fas fa-user-circle fa-fw"></i>作者</a></span>&nbsp;<span class="post-category">出版于  <a href="/categories/cpp%E5%A4%9A%E7%BA%BF%E7%A8%8B%E5%BC%82%E6%AD%A5%E4%B8%8E%E5%B9%B6%E5%8F%91/"><i class="far fa-folder fa-fw"></i>CPP多线程异步与并发</a></span></div>
                <div class="post-meta-line"><span><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2022-08-23">2022-08-23</time></span>&nbsp;<span><i class="fas fa-pencil-alt fa-fw"></i>&nbsp;约 4845 字</span>&nbsp;
                    <span><i class="far fa-clock fa-fw"></i>&nbsp;预计阅读 10 分钟</span>&nbsp;</div>
            </div>
            
            <hr><div class="details toc" id="toc-static"  data-kept="">
                    <div class="details-summary toc-title">
                        <span>目录</span>
                        <span><i class="details-icon fas fa-angle-right"></i></span>
                    </div>
                    <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents">
  <ul>
    <li><a href="#1数据竞争">1、数据竞争</a></li>
    <li><a href="#2stdmutex">2、std::mutex</a></li>
    <li><a href="#3stdlock_guard">3、std::lock_guard</a></li>
    <li><a href="#4stdunique_lock">4、std::unique_lock</a></li>
    <li><a href="#5多个对象-多个锁">5、多个对象-多个锁</a></li>
    <li><a href="#6死锁">6、死锁</a></li>
    <li><a href="#7封装多线程安全的数据结构">7、封装多线程安全的数据结构</a></li>
    <li><a href="#8读写锁">8、读写锁</a></li>
  </ul>
</nav></div>
                </div><div class="content" id="content"><h2 id="1数据竞争">1、数据竞争</h2>
<p>两个线程试图往同一个数组中放数据，程序直接崩溃了，这是为什么呢？</p>
<p>假设vector容器的长度为4，但是现在线程1想要额外追加数据，那么我们就要扩充vector容器的长度，然后就把长度为4的vector给delete掉了，然后线程2也看到了长度为4的vector，它的想法和线程1一样，也想扩充vector，然后也把长度为4的vector给delete掉了。</p>
<p>那么此时出现了double delete(也是double free)，导致内存泄漏，程序崩溃。</p>
<p>所以vector不是多线程安全(MT-safe)的容器。</p>
<p>多个线程同时访问同一个vector会出现数据竞争(data-race)的现象。</p>
<h2 id="2stdmutex">2、std::mutex</h2>
<p>**数据竞争这个问题的解决方法是通过std::mutex，**我们可以通过上锁防止多个线程同时进入某一个代码段。</p>
<p>当我们调用std::mutex的lock时，会检查mutex是否已经上锁。</p>
<p>如果没有锁定，那么mutex会进行上锁。</p>
<p>如果已经锁定，则陷入等待状态，直到mutex被另一个线程解锁后，才再次上锁。</p>
<p>而调用unlock()则会进行解锁。</p>
<p><strong>这样，就可以确保lock和unlock之间的代码段，在同一时间只有一个线程在执行，从而避免数据竞争。</strong></p>
<p>示例代码如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="cp">#include</span><span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;thread&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;chrono&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;vector&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;mutex&gt;</span><span class="cp">
</span><span class="cp"></span><span class="cm">/*
</span><span class="cm">并发 指单个cpu同时处理多个线程任务，cpu在反复切换任务线程，实际还是串行化的；
</span><span class="cm">并行 指多个cpu同时处理多个线程任务，cpu可以同时处理不同的任务，异步处理；
</span><span class="cm">互斥量：多个线程访问同一个数据
</span><span class="cm">*/</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
	<span class="cm">/*
</span><span class="cm">	多线程打架：
</span><span class="cm">	两个线程试图往一个线程中传递数据。程序直接崩溃。
</span><span class="cm">	vector不是多线程安全容器。
</span><span class="cm">	因为多个线程同时访问一个vector会出现数据竞争的现象。
</span><span class="cm">	解决方法：
</span><span class="cm">	我们可以通过mutex上锁，防止多个线程同时进入同一个vector
</span><span class="cm">	*/</span>
	<span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">&gt;</span><span class="n">v</span><span class="p">;</span>
	<span class="n">std</span><span class="o">::</span><span class="n">mutex</span> <span class="n">mtx</span><span class="p">;</span>
	<span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t1</span><span class="p">([</span><span class="o">&amp;</span><span class="p">]()</span> <span class="p">{</span>
		<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">1000</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span>
		<span class="p">{</span>
			<span class="cm">/*
</span><span class="cm">			lock与unlock是上锁和解锁，它们的作用是确保在同一时间只有一个线程在执行，
</span><span class="cm">			从而避免数据竞争。
</span><span class="cm">			*/</span>
			<span class="n">mtx</span><span class="p">.</span><span class="n">lock</span><span class="p">();</span>
			<span class="n">v</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>
			<span class="n">mtx</span><span class="p">.</span><span class="n">unlock</span><span class="p">();</span>
		<span class="p">}</span>
		<span class="p">});</span>
	<span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t2</span><span class="p">([</span><span class="o">&amp;</span><span class="p">]()</span> <span class="p">{</span>
		<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">1000</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span>
		<span class="p">{</span>
			<span class="n">mtx</span><span class="p">.</span><span class="n">lock</span><span class="p">();</span>
			<span class="n">v</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="mi">2</span><span class="p">);</span>
			<span class="n">mtx</span><span class="p">.</span><span class="n">unlock</span><span class="p">();</span>
		<span class="p">}</span>
		<span class="p">});</span>
	<span class="n">t1</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
	<span class="n">t2</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
	<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div><h2 id="3stdlock_guard">3、std::lock_guard</h2>
<p>如果我们忘记解锁，那么程序依旧会出错，所以为了确保我们忘记解锁，程序依旧不会出错，我们可以通过一个更容易且不出错的方式修改一下代码，<strong>我们可以使用std::lock_guard。</strong></p>
<p>我们可以将锁视为一种资源，上锁即为获取，解锁即为释放。</p>
<p><strong>std::lock_guard就是这样的一个工具类，它的构造函数会调用lock(上锁)，析构函数会调用unlock(解锁)。从而退出函数作用域时能够自动解锁，避免程序员粗心忘记解锁。</strong></p>
<p>示例代码：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="cp">#include</span><span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;thread&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;chrono&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;vector&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;mutex&gt;</span><span class="cp">
</span><span class="cp"></span><span class="cm">/*
</span><span class="cm">并发 指单个cpu同时处理多个线程任务，cpu在反复切换任务线程，实际还是串行化的；
</span><span class="cm">并行 指多个cpu同时处理多个线程任务，cpu可以同时处理不同的任务，异步处理；
</span><span class="cm">互斥量：多个线程访问同一个数据
</span><span class="cm">*/</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
	<span class="cm">/*
</span><span class="cm">	我们可以将锁视为一种资源，上锁即获取，解锁即为释放。
</span><span class="cm">	std::lock_guard它的构造函数会调用上锁，而它的析构函数会调用解锁，
</span><span class="cm">	也就是说在退出函数作用域时就会自动帮助我们解锁，从而避免我们忘记解锁。
</span><span class="cm">	*/</span>
	<span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">&gt;</span><span class="n">v</span><span class="p">;</span>
	<span class="n">std</span><span class="o">::</span><span class="n">mutex</span> <span class="n">mtx</span><span class="p">;</span>
	<span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t1</span><span class="p">([</span><span class="o">&amp;</span><span class="p">]()</span> <span class="p">{</span>
		<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">1000</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span>
		<span class="p">{</span>
			<span class="n">std</span><span class="o">::</span><span class="n">lock_guard</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">mutex</span><span class="o">&gt;</span><span class="n">grd</span><span class="p">(</span><span class="n">mtx</span><span class="p">);</span>
			<span class="n">v</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>
		<span class="p">}</span>
		<span class="p">});</span>
	<span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t2</span><span class="p">([</span><span class="o">&amp;</span><span class="p">]()</span> <span class="p">{</span>
		<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">1000</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span>
		<span class="p">{</span>
			<span class="n">std</span><span class="o">::</span><span class="n">lock_guard</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">mutex</span><span class="o">&gt;</span><span class="n">grd</span><span class="p">(</span><span class="n">mtx</span><span class="p">);</span>
			<span class="n">v</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="mi">2</span><span class="p">);</span>
		<span class="p">}</span>
		<span class="p">});</span>
	<span class="n">t1</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
	<span class="n">t2</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>

	<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div><h2 id="4stdunique_lock">4、std::unique_lock</h2>
<p><strong>std::lock_guard存在一个问题，就是无法提前解锁，std::lock_guard在析构时调用unlock，但是有时我们想提前解锁，这时候我们就可以使用unique_lock。</strong></p>
<p>unique_lock它额外存储了一个flag表示是否已经释放。它会在析构时检测这个flag，如果没有释放，则调用unlock，否则不调用。</p>
<p><strong>然后也可以直接调用unlock用来提前解锁，即使忘记解锁也没有关系，退出作用域时它还会自动检查一遍要不要解锁。</strong></p>
<p>示例代码如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="cp">#include</span><span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;thread&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;chrono&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;vector&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;mutex&gt;</span><span class="cp">
</span><span class="cp"></span><span class="cm">/*
</span><span class="cm">并发 指单个cpu同时处理多个线程任务，cpu在反复切换任务线程，实际还是串行化的；
</span><span class="cm">并行 指多个cpu同时处理多个线程任务，cpu可以同时处理不同的任务，异步处理；
</span><span class="cm">互斥量：多个线程访问同一个数据
</span><span class="cm">*/</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
	<span class="cm">/*
</span><span class="cm">	std::unique_lock它的自由度更高，它可以在中途解锁。
</span><span class="cm">	当std::lock_guard在调用析构函数的unlock时，这时我们希望提前unlock，
</span><span class="cm">	然后我们就可以使用unique_lock，它额外存储了一个flag表示是否已经被释放，
</span><span class="cm">	它会在析构时，检测这个flag，如果没有释放则会调用unlock，否则不调用。
</span><span class="cm">	我们可以直接调用unique中的unlock进行提前解锁，即便忘记解锁，退出作用域时，
</span><span class="cm">	它会自动检测是否要不要解锁。
</span><span class="cm">	*/</span>
	<span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">&gt;</span><span class="n">v</span><span class="p">;</span>
	<span class="n">std</span><span class="o">::</span><span class="n">mutex</span> <span class="n">mtx</span><span class="p">;</span>
	<span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t1</span><span class="p">([</span><span class="o">&amp;</span><span class="p">]()</span> <span class="p">{</span>
		<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">1000</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span>
		<span class="p">{</span>
			<span class="n">std</span><span class="o">::</span><span class="n">unique_lock</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">mutex</span><span class="o">&gt;</span><span class="n">u</span><span class="p">(</span><span class="n">mtx</span><span class="p">);</span>
			<span class="n">v</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>
		<span class="p">}</span>
		<span class="p">});</span>
	<span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t2</span><span class="p">([</span><span class="o">&amp;</span><span class="p">]()</span> <span class="p">{</span>
		<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">1000</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span>
		<span class="p">{</span>
			<span class="n">std</span><span class="o">::</span><span class="n">unique_lock</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">mutex</span><span class="o">&gt;</span><span class="n">u</span><span class="p">(</span><span class="n">mtx</span><span class="p">);</span>
			<span class="n">v</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="mi">2</span><span class="p">);</span>
			<span class="n">u</span><span class="p">.</span><span class="n">unlock</span><span class="p">();</span>
			<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;hello world&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
			<span class="c1">//u.lock();//如果需要可以上锁
</span><span class="c1"></span>		<span class="p">}</span>
		<span class="p">});</span>
	<span class="n">t1</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
	<span class="n">t2</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>

	<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div><p>另外std::unique_lock的构造函数还可以有一个额外的参数，那就是std::defer_lock。</p>
<p>指定了这个参数的话，std::unique_lock不会再构造函数中调用lock(上锁),需要自己手动调用lock()方法。</p>
<p>但是即便我们忘记unlock(解锁),也能够自动调用unlock。</p>
<p>示例代码：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="cp">#include</span><span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;thread&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;chrono&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;vector&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;mutex&gt;</span><span class="cp">
</span><span class="cp"></span><span class="cm">/*
</span><span class="cm">并发 指单个cpu同时处理多个线程任务，cpu在反复切换任务线程，实际还是串行化的；
</span><span class="cm">并行 指多个cpu同时处理多个线程任务，cpu可以同时处理不同的任务，异步处理；
</span><span class="cm">互斥量：多个线程访问同一个数据
</span><span class="cm">*/</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
	<span class="cm">/*
</span><span class="cm">	std::unique_lock它的自由度更高，它可以在中途解锁。
</span><span class="cm">	当std::lock_guard在调用析构函数的unlock时，这时我们希望提前unlock，
</span><span class="cm">	然后我们就可以使用unique_lock，它额外存储了一个flag表示是否已经被释放，
</span><span class="cm">	它会在析构时，检测这个flag，如果没有释放则会调用unlock，否则不调用。
</span><span class="cm">	我们可以直接调用unique中的unlock进行提前解锁，即便忘记解锁，退出作用域时，
</span><span class="cm">	它会自动检测是否要不要解锁。
</span><span class="cm">	*/</span>
	<span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">&gt;</span><span class="n">v</span><span class="p">;</span>
	<span class="n">std</span><span class="o">::</span><span class="n">mutex</span> <span class="n">mtx</span><span class="p">;</span>
	<span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t1</span><span class="p">([</span><span class="o">&amp;</span><span class="p">]()</span> <span class="p">{</span>
		<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">1000</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span>
		<span class="p">{</span>
			<span class="n">std</span><span class="o">::</span><span class="n">unique_lock</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">mutex</span><span class="o">&gt;</span><span class="n">u</span><span class="p">(</span><span class="n">mtx</span><span class="p">);</span>
			<span class="n">v</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>
		<span class="p">}</span>
		<span class="p">});</span>
	<span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t2</span><span class="p">([</span><span class="o">&amp;</span><span class="p">]()</span> <span class="p">{</span>
		<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">1000</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span>
		<span class="p">{</span>
			<span class="n">std</span><span class="o">::</span><span class="n">unique_lock</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">mutex</span><span class="o">&gt;</span><span class="n">u</span><span class="p">(</span><span class="n">mtx</span><span class="p">,</span><span class="n">std</span><span class="o">::</span><span class="n">defer_lock</span><span class="p">);</span>
            <span class="n">std</span><span class="o">::</span><span class="n">cout</span><span class="o">&lt;&lt;</span><span class="s">&#34;before lock&#34;</span><span class="o">&lt;&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
            <span class="n">u</span><span class="p">.</span><span class="n">lock</span><span class="p">();</span>
			<span class="n">v</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="mi">2</span><span class="p">);</span>
			<span class="n">u</span><span class="p">.</span><span class="n">unlock</span><span class="p">();</span>
			<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;outside of lock&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
		<span class="p">}</span>
		<span class="p">});</span>
	<span class="n">t1</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
	<span class="n">t2</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>

	<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div><h2 id="5多个对象-多个锁">5、多个对象-多个锁</h2>
<p>一个锁锁定一个数组，另外一把锁锁定另一个数组。</p>
<p>不同的对象上，各有一个锁独立地上锁，可以避免不必要的锁定，提升高并发的性能。</p>
<p>同时用一个{}包住std::lock_guard，限制其变量的作用域。</p>
<p>从而可以让它在}之前析构并调用unlock方法，也避免了和下面一个lock_guard变量名的冲突。</p>
<p>示例代码如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="cp">#include</span><span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;thread&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;chrono&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;vector&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;mutex&gt;</span><span class="cp">
</span><span class="cp"></span><span class="cm">/*
</span><span class="cm">并发 指单个cpu同时处理多个线程任务，cpu在反复切换任务线程，实际还是串行化的；
</span><span class="cm">并行 指多个cpu同时处理多个线程任务，cpu可以同时处理不同的任务，异步处理；
</span><span class="cm">互斥量：多个线程访问同一个数据
</span><span class="cm">*/</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
	<span class="cm">/*
</span><span class="cm">	多个vector，配多个mutex。
</span><span class="cm">	mtx1锁住v1，mtx2锁住v2,不同的对象上各有一个mutex，独立的上锁，可以避免不必要的锁定，
</span><span class="cm">	提升高并发的性能。
</span><span class="cm">	同时还用到了{}包住std::lock_guard，限制变量的作用域，从而可以让它在}之前析构
</span><span class="cm">	并且调用unlock
</span><span class="cm">	*/</span>
	<span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">&gt;</span><span class="n">v1</span><span class="p">;</span>
	<span class="n">std</span><span class="o">::</span><span class="n">mutex</span> <span class="n">mtx1</span><span class="p">;</span>
	
	<span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">&gt;</span><span class="n">v2</span><span class="p">;</span>
	<span class="n">std</span><span class="o">::</span><span class="n">mutex</span> <span class="n">mtx2</span><span class="p">;</span>
	
	<span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t1</span><span class="p">([</span><span class="o">&amp;</span><span class="p">]()</span> <span class="p">{</span>
		<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">1000</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span>
		<span class="p">{</span>
			<span class="p">{</span>
				<span class="n">std</span><span class="o">::</span><span class="n">lock_guard</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">mutex</span><span class="o">&gt;</span><span class="n">gud</span><span class="p">(</span><span class="n">mtx1</span><span class="p">);</span>
				<span class="n">v1</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>
			<span class="p">}</span>
			<span class="p">{</span>
				<span class="n">std</span><span class="o">::</span><span class="n">lock_guard</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">mutex</span><span class="o">&gt;</span><span class="n">gud</span><span class="p">(</span><span class="n">mtx2</span><span class="p">);</span>
				<span class="n">v2</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span>
			<span class="p">}</span>
		<span class="p">}</span>
		<span class="p">});</span>

	<span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t2</span><span class="p">([</span><span class="o">&amp;</span><span class="p">]()</span> <span class="p">{</span>
		<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">1000</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span>
		<span class="p">{</span>
			<span class="p">{</span>
				<span class="n">std</span><span class="o">::</span><span class="n">lock_guard</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">mutex</span><span class="o">&gt;</span><span class="n">gud</span><span class="p">(</span><span class="n">mtx1</span><span class="p">);</span>
				<span class="n">v1</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="mi">2</span><span class="p">);</span>
			<span class="p">}</span>
			<span class="p">{</span>
				<span class="n">std</span><span class="o">::</span><span class="n">lock_guard</span><span class="o">&lt;</span><span class="n">std</span><span class="o">::</span><span class="n">mutex</span><span class="o">&gt;</span><span class="n">gud</span><span class="p">(</span><span class="n">mtx2</span><span class="p">);</span>
				<span class="n">v2</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="mi">2</span><span class="p">);</span>
			<span class="p">}</span>
		<span class="p">}</span>
		<span class="p">});</span>
	<span class="n">t1</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
	<span class="n">t2</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
	<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div><h2 id="6死锁">6、死锁</h2>
<p>由于同时执行的两个线程，它们中发生的指令不一定是同步的，因此有可能出现这种情况：</p>
<p>线程1中的mutex1执行上锁，线程2的mutex2执行上锁，</p>
<p>线程1中的mutex2执行上锁，失败，陷入等待，线程2执行mutex1上锁，失败，陷入等待。</p>
<p>双方都在等待对方释放锁，但是因为等待而无法释放锁，从而要无限制等待下去，这种现象称为死锁。</p>
<p>死锁代码如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="cp">#include</span><span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;thread&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;chrono&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;vector&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;mutex&gt;</span><span class="cp">
</span><span class="cp"></span><span class="cm">/*
</span><span class="cm">并发 指单个cpu同时处理多个线程任务，cpu在反复切换任务线程，实际还是串行化的；
</span><span class="cm">并行 指多个cpu同时处理多个线程任务，cpu可以同时处理不同的任务，异步处理；
</span><span class="cm">互斥量：多个线程访问同一个数据
</span><span class="cm">*/</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
    <span class="n">std</span><span class="o">::</span><span class="n">mutex</span> <span class="n">mtx1</span><span class="p">;</span>
    <span class="n">std</span><span class="o">::</span><span class="n">mutex</span> <span class="n">mtx2</span><span class="p">;</span>
    <span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t1</span><span class="p">([</span><span class="o">&amp;</span><span class="p">](){</span>
        <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span><span class="n">i</span><span class="o">&lt;</span><span class="mi">1000</span><span class="p">;</span><span class="n">i</span><span class="o">++</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="n">mtx1</span><span class="p">.</span><span class="n">lock</span><span class="p">();</span>
            <span class="n">mtx2</span><span class="p">.</span><span class="n">lock</span><span class="p">();</span>
            <span class="n">mtx1</span><span class="p">.</span><span class="n">unlock</span><span class="p">();</span>
            <span class="n">mtx2</span><span class="p">.</span><span class="n">unlock</span><span class="p">();</span>
        <span class="p">}</span>
    <span class="p">});</span>
    <span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t2</span><span class="p">([</span><span class="o">&amp;</span><span class="p">](){</span>
        <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span><span class="n">i</span><span class="o">&lt;</span><span class="mi">1000</span><span class="p">;</span><span class="n">i</span><span class="o">++</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="n">mtx2</span><span class="p">.</span><span class="n">lock</span><span class="p">();</span>
            <span class="n">mtx1</span><span class="p">.</span><span class="n">lock</span><span class="p">();</span>
            <span class="n">mtx1</span><span class="p">.</span><span class="n">unlock</span><span class="p">();</span>
            <span class="n">mtx2</span><span class="p">.</span><span class="n">unlock</span><span class="p">();</span>
        <span class="p">}</span>
    <span class="p">});</span>
    <span class="n">t1</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
    <span class="n">t2</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div><p>死锁的解决方法1：保证双方上锁的顺序一致。</p>
<p>示例代码如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="cp">#include</span><span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;thread&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;chrono&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;vector&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;mutex&gt;</span><span class="cp">
</span><span class="cp"></span><span class="cm">/*
</span><span class="cm">并发 指单个cpu同时处理多个线程任务，cpu在反复切换任务线程，实际还是串行化的；
</span><span class="cm">并行 指多个cpu同时处理多个线程任务，cpu可以同时处理不同的任务，异步处理；
</span><span class="cm">互斥量：多个线程访问同一个数据
</span><span class="cm">*/</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
    <span class="n">std</span><span class="o">::</span><span class="n">mutex</span> <span class="n">mtx1</span><span class="p">;</span>
    <span class="n">std</span><span class="o">::</span><span class="n">mutex</span> <span class="n">mtx2</span><span class="p">;</span>
    <span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t1</span><span class="p">([</span><span class="o">&amp;</span><span class="p">](){</span>
        <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span><span class="n">i</span><span class="o">&lt;</span><span class="mi">1000</span><span class="p">;</span><span class="n">i</span><span class="o">++</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="n">mtx1</span><span class="p">.</span><span class="n">lock</span><span class="p">();</span>
            <span class="n">mtx2</span><span class="p">.</span><span class="n">lock</span><span class="p">();</span>
            <span class="n">mtx1</span><span class="p">.</span><span class="n">unlock</span><span class="p">();</span>
            <span class="n">mtx2</span><span class="p">.</span><span class="n">unlock</span><span class="p">();</span>
        <span class="p">}</span>
    <span class="p">});</span>
    <span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t2</span><span class="p">([</span><span class="o">&amp;</span><span class="p">](){</span>
        <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span><span class="n">i</span><span class="o">&lt;</span><span class="mi">1000</span><span class="p">;</span><span class="n">i</span><span class="o">++</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="n">mtx1</span><span class="p">.</span><span class="n">lock</span><span class="p">();</span>
            <span class="n">mtx2</span><span class="p">.</span><span class="n">lock</span><span class="p">();</span>
            <span class="n">mtx2</span><span class="p">.</span><span class="n">unlock</span><span class="p">();</span>
            <span class="n">mtx1</span><span class="p">.</span><span class="n">unlock</span><span class="p">();</span>
        <span class="p">}</span>
    <span class="p">});</span>
    <span class="n">t1</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
    <span class="n">t2</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div><p>死锁的解决方法2：使用std::lock同时对多个上锁。</p>
<p>如果没办法保证上锁的顺序一致，可以用标准库std::lock(mtx1,mtx2)函数，一次性对多个mutex上锁。</p>
<p>它接受任意多个mutex作为参数，并且它保证在无论任意线程中调用的顺序是否相同，都不会产生死锁问题。</p>
<p>示例代码如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="cp">#include</span><span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;thread&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;chrono&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;vector&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;mutex&gt;</span><span class="cp">
</span><span class="cp"></span><span class="cm">/*
</span><span class="cm">并发 指单个cpu同时处理多个线程任务，cpu在反复切换任务线程，实际还是串行化的；
</span><span class="cm">并行 指多个cpu同时处理多个线程任务，cpu可以同时处理不同的任务，异步处理；
</span><span class="cm">互斥量：多个线程访问同一个数据
</span><span class="cm">*/</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
    <span class="n">std</span><span class="o">::</span><span class="n">mutex</span> <span class="n">mtx1</span><span class="p">;</span>
    <span class="n">std</span><span class="o">::</span><span class="n">mutex</span> <span class="n">mtx2</span><span class="p">;</span>
    <span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t1</span><span class="p">([</span><span class="o">&amp;</span><span class="p">](){</span>
        <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span><span class="n">i</span><span class="o">&lt;</span><span class="mi">1000</span><span class="p">;</span><span class="n">i</span><span class="o">++</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="n">std</span><span class="o">::</span><span class="n">lock</span><span class="p">(</span><span class="n">mtx1</span><span class="p">,</span><span class="n">mtx2</span><span class="p">);</span>
            <span class="n">mtx1</span><span class="p">.</span><span class="n">unlock</span><span class="p">();</span>
            <span class="n">mtx2</span><span class="p">.</span><span class="n">unlock</span><span class="p">();</span>
        <span class="p">}</span>
    <span class="p">});</span>
    <span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t2</span><span class="p">([</span><span class="o">&amp;</span><span class="p">](){</span>
        <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span><span class="n">i</span><span class="o">&lt;</span><span class="mi">1000</span><span class="p">;</span><span class="n">i</span><span class="o">++</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="n">std</span><span class="o">::</span><span class="n">lock</span><span class="p">(</span><span class="n">mtx2</span><span class="p">,</span><span class="n">mtx1</span><span class="p">);</span>
            <span class="n">mtx2</span><span class="p">.</span><span class="n">unlock</span><span class="p">();</span>
            <span class="n">mtx1</span><span class="p">.</span><span class="n">unlock</span><span class="p">();</span>
        <span class="p">}</span>
    <span class="p">});</span>
    <span class="n">t1</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
    <span class="n">t2</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div><p>死锁的解决办法3：std::scoped_lock</p>
<p>在上述代码中，如果我们忘记解锁那么就无法释放资源，那么就会导致内存泄漏。</p>
<p>所以为了简化我们的代码，并且不用手动解锁，我们可以使用std::scoped_lock，它可以自动帮助我们上锁和解锁。</p>
<p>示例代码如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="cp">#include</span><span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;thread&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;chrono&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;vector&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;mutex&gt;</span><span class="cp">
</span><span class="cp"></span><span class="cm">/*
</span><span class="cm">并发 指单个cpu同时处理多个线程任务，cpu在反复切换任务线程，实际还是串行化的；
</span><span class="cm">并行 指多个cpu同时处理多个线程任务，cpu可以同时处理不同的任务，异步处理；
</span><span class="cm">互斥量：多个线程访问同一个数据
</span><span class="cm">*/</span>
<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
    <span class="n">std</span><span class="o">::</span><span class="n">mutex</span> <span class="n">mtx1</span><span class="p">;</span>
    <span class="n">std</span><span class="o">::</span><span class="n">mutex</span> <span class="n">mtx2</span><span class="p">;</span>
    <span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t1</span><span class="p">([</span><span class="o">&amp;</span><span class="p">](){</span>
        <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span><span class="n">i</span><span class="o">&lt;</span><span class="mi">1000</span><span class="p">;</span><span class="n">i</span><span class="o">++</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="n">std</span><span class="o">::</span><span class="n">scoped_lock</span> <span class="n">grd</span><span class="p">(</span><span class="n">mtx1</span><span class="p">,</span><span class="n">mtx2</span><span class="p">);</span>
            <span class="c1">//do something
</span><span class="c1"></span>        <span class="p">}</span>
    <span class="p">});</span>
    <span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t2</span><span class="p">([</span><span class="o">&amp;</span><span class="p">](){</span>
        <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span><span class="n">i</span><span class="o">&lt;</span><span class="mi">1000</span><span class="p">;</span><span class="n">i</span><span class="o">++</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="n">std</span><span class="o">::</span><span class="n">scoped_lock</span> <span class="n">grd</span><span class="p">(</span><span class="n">mtx2</span><span class="p">,</span><span class="n">mtx1</span><span class="p">);</span>
            <span class="c1">//do something
</span><span class="c1"></span>        <span class="p">}</span>
    <span class="p">});</span>
    <span class="n">t1</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
    <span class="n">t2</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div><p><strong>注意：std::scoped_lock(区域锁)是C++17中的具有隐式类模板参数推导的机制，传入构造函数的对象会自动匹配。</strong></p>
<p><strong>但是我们vs2019默认是C++11，所以我们需要在vs2019中找到项目的属性，然后在语言中配置C++17的标准就行啦。</strong></p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://raw.githubusercontent.com/jjking20010901/typora/master/img202208231531493.png"
        data-srcset="https://raw.githubusercontent.com/jjking20010901/typora/master/img202208231531493.png, https://raw.githubusercontent.com/jjking20010901/typora/master/img202208231531493.png 1.5x, https://raw.githubusercontent.com/jjking20010901/typora/master/img202208231531493.png 2x"
        data-sizes="auto"
        alt="https://raw.githubusercontent.com/jjking20010901/typora/master/img202208231531493.png"
        title="image-20220823153112410" /></p>
<h2 id="7封装多线程安全的数据结构">7、封装多线程安全的数据结构</h2>
<p>之前说过vector容器不是多线程安全的容器，在多个线程中同时访问同一个vector会出现数据竞争的现象。</p>
<p>那么如下我会简单的封装一下多线程安全的vector容器。</p>
<p>代码如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="cp">#include</span><span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;vector&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;mutex&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;thread&gt;</span><span class="cp">
</span><span class="cp"></span>
<span class="c1">//多线程下安全的vector类
</span><span class="c1"></span><span class="k">class</span> <span class="nc">MTVector</span>
<span class="p">{</span>
<span class="k">public</span><span class="o">:</span>
	<span class="kt">void</span> <span class="n">push_back</span><span class="p">(</span><span class="kt">int</span> <span class="n">val</span><span class="p">)</span>
	<span class="p">{</span>
		<span class="n">m_mtx</span><span class="p">.</span><span class="n">lock</span><span class="p">();</span>
		<span class="n">m_MTVector</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="n">val</span><span class="p">);</span>
		<span class="n">m_mtx</span><span class="p">.</span><span class="n">unlock</span><span class="p">();</span>
	<span class="p">}</span>
	<span class="n">size_t</span> <span class="nf">size</span><span class="p">()</span> <span class="k">const</span> 
	<span class="p">{</span>
		<span class="n">m_mtx</span><span class="p">.</span><span class="n">lock</span><span class="p">();</span>
		<span class="k">auto</span> <span class="n">ret</span> <span class="o">=</span> <span class="n">m_MTVector</span><span class="p">.</span><span class="n">size</span><span class="p">();</span>
		<span class="n">m_mtx</span><span class="p">.</span><span class="n">unlock</span><span class="p">();</span>
		<span class="k">return</span> <span class="n">ret</span><span class="p">;</span>
	<span class="p">}</span>

<span class="k">private</span><span class="o">:</span>
	<span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">&gt;</span><span class="n">m_MTVector</span><span class="p">;</span>
	<span class="c1">//由于vector的size是const，无法修改的，但是上锁和解锁是要求修改size大小，
</span><span class="c1"></span>	<span class="c1">//所以我们要加入mutable，让其允许mutex改变。
</span><span class="c1"></span>	<span class="k">mutable</span> <span class="n">std</span><span class="o">::</span><span class="n">mutex</span> <span class="n">m_mtx</span><span class="p">;</span>
<span class="p">};</span>


<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
	<span class="n">MTVector</span> <span class="n">v1</span><span class="p">;</span>
	<span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t1</span><span class="p">([</span><span class="o">&amp;</span><span class="p">]()</span> <span class="p">{</span>
		<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">1000</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span>
		<span class="p">{</span>
			<span class="n">v1</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="n">i</span><span class="p">);</span>
		<span class="p">}</span>
		<span class="p">});</span>
	<span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t2</span><span class="p">([</span><span class="o">&amp;</span><span class="p">]()</span> <span class="p">{</span>
		<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">1000</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span>
		<span class="p">{</span>
			<span class="n">v1</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="n">i</span> <span class="o">+</span> <span class="mi">1000</span><span class="p">);</span>
		<span class="p">}</span>
		<span class="p">});</span>
	<span class="n">t1</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
	<span class="n">t2</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
	<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;v1 size:&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">v1</span><span class="p">.</span><span class="n">size</span><span class="p">()</span> <span class="o">&lt;&lt;</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
	<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div><h2 id="8读写锁">8、读写锁</h2>
<p>针对读可以共享，写必须独占，且写和读不能共存，于是就有了读写锁(std::shared_mutex)。</p>
<p>读写锁允许的状态有：</p>
<ul>
<li>n个人读取，没人写入。</li>
<li>1个人写入，没有人读取。</li>
<li>没有人读取，也没有人写入。</li>
</ul>
<p>还是以上述封装的多线程安全容器为例，在代码中加入读写锁，修改后的代码如下：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-CPP" data-lang="CPP"><span class="cp">#include</span><span class="cpf">&lt;iostream&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;vector&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;mutex&gt;</span><span class="cp">
</span><span class="cp">#include</span><span class="cpf">&lt;thread&gt;</span><span class="cp">
</span><span class="cp"></span>
<span class="c1">//多线程下安全的vector类
</span><span class="c1"></span><span class="k">class</span> <span class="nc">MTVector</span>
<span class="p">{</span>
<span class="k">public</span><span class="o">:</span>
	<span class="kt">void</span> <span class="n">push_back</span><span class="p">(</span><span class="kt">int</span> <span class="n">val</span><span class="p">)</span>
	<span class="p">{</span>
		<span class="n">m_mtx</span><span class="p">.</span><span class="n">lock</span><span class="p">();</span>
		<span class="n">m_MTVector</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="n">val</span><span class="p">);</span>
		<span class="n">m_mtx</span><span class="p">.</span><span class="n">unlock</span><span class="p">();</span>
	<span class="p">}</span>
	<span class="n">size_t</span> <span class="nf">size</span><span class="p">()</span> <span class="k">const</span> 
	<span class="p">{</span>
		<span class="n">m_mtx</span><span class="p">.</span><span class="n">lock_shared</span><span class="p">();</span>
		<span class="k">auto</span> <span class="n">ret</span> <span class="o">=</span> <span class="n">m_MTVector</span><span class="p">.</span><span class="n">size</span><span class="p">();</span>
		<span class="n">m_mtx</span><span class="p">.</span><span class="n">unlock_shared</span><span class="p">();</span>
		<span class="k">return</span> <span class="n">ret</span><span class="p">;</span>
	<span class="p">}</span>

<span class="k">private</span><span class="o">:</span>
	<span class="n">std</span><span class="o">::</span><span class="n">vector</span><span class="o">&lt;</span><span class="kt">int</span><span class="o">&gt;</span><span class="n">m_MTVector</span><span class="p">;</span>
	<span class="c1">//由于vector的size是const，无法修改的，但是上锁和解锁是要求修改size大小，
</span><span class="c1"></span>	<span class="c1">//所以我们要加入mutable，让其允许mutex改变。
</span><span class="c1"></span>	<span class="k">mutable</span> <span class="n">std</span><span class="o">::</span><span class="n">shared_mutex</span> <span class="n">m_mtx</span><span class="p">;</span>
<span class="p">};</span>


<span class="kt">int</span> <span class="nf">main</span><span class="p">()</span>
<span class="p">{</span>
	<span class="n">MTVector</span> <span class="n">v1</span><span class="p">;</span>
	<span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t1</span><span class="p">([</span><span class="o">&amp;</span><span class="p">]()</span> <span class="p">{</span>
		<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">1000</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span>
		<span class="p">{</span>
			<span class="n">v1</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="n">i</span><span class="p">);</span>
		<span class="p">}</span>
		<span class="p">});</span>
	<span class="n">std</span><span class="o">::</span><span class="kr">thread</span> <span class="n">t2</span><span class="p">([</span><span class="o">&amp;</span><span class="p">]()</span> <span class="p">{</span>
		<span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">1000</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span>
		<span class="p">{</span>
			<span class="n">v1</span><span class="p">.</span><span class="n">push_back</span><span class="p">(</span><span class="n">i</span> <span class="o">+</span> <span class="mi">1000</span><span class="p">);</span>
		<span class="p">}</span>
		<span class="p">});</span>
	<span class="n">t1</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
	<span class="n">t2</span><span class="p">.</span><span class="n">join</span><span class="p">();</span>
	<span class="n">std</span><span class="o">::</span><span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;v1 size:&#34;</span> <span class="o">&lt;&lt;</span> <span class="n">v1</span><span class="p">.</span><span class="n">size</span><span class="p">()</span> <span class="o">&lt;&lt;</span> <span class="n">std</span><span class="o">::</span><span class="n">endl</span><span class="p">;</span>
	<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div><p><strong>注意：</strong></p>
<p><strong>c++ 17 新出的具有独占模式和共享模式的锁。共享模式能够被 shared_lock 占有。</strong></p>
<p><strong>std::shared_mutex 是读写锁，提供两种访问权限的控制：共享性（shared）和排他性（exclusive）。通过lock/try_lock获取排他性访问权限，通过lock_shared/try_lock_shared获取共享性访问权限。这样的设置对于区分不同线程的读写操作特别有用。shared_mutex是c++17中引入的，使用时需要注意编译器版本。</strong></p>
</div><div class="post-footer" id="post-footer">
    <div class="post-info"><div class="post-info-tag"><span><a href="/tags/%E4%BA%92%E6%96%A5%E9%87%8F/">互斥量</a>
                </span></div><div class="post-info-line"><div class="post-info-mod">
                <span>更新于 2022-08-23</span>
            </div><div class="post-info-mod"></div>
        </div><div class="post-info-share">
            <span><a href="javascript:void(0);" title="分享到 Twitter" data-sharer="twitter" data-url="https://acking-you.gitee.io/posts/%C3%A4%C2%BA%C3%A6%C3%A9/" data-title="互斥量" data-hashtags="互斥量"><i class="fab fa-twitter fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Facebook" data-sharer="facebook" data-url="https://acking-you.gitee.io/posts/%C3%A4%C2%BA%C3%A6%C3%A9/" data-hashtag="互斥量"><i class="fab fa-facebook-square fa-fw"></i></a><a href="javascript:void(0);" title="分享到 WhatsApp" data-sharer="whatsapp" data-url="https://acking-you.gitee.io/posts/%C3%A4%C2%BA%C3%A6%C3%A9/" data-title="互斥量" data-web><i class="fab fa-whatsapp fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Line" data-sharer="line" data-url="https://acking-you.gitee.io/posts/%C3%A4%C2%BA%C3%A6%C3%A9/" data-title="互斥量"><i class="fab fa-line fa-fw"></i></a><a href="javascript:void(0);" title="分享到 微博" data-sharer="weibo" data-url="https://acking-you.gitee.io/posts/%C3%A4%C2%BA%C3%A6%C3%A9/" data-title="互斥量" data-image="https://w.wallhaven.cc/full/dp/wallhaven-dplz6l.jpg"><i class="fab fa-weibo fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Myspace" data-sharer="myspace" data-url="https://acking-you.gitee.io/posts/%C3%A4%C2%BA%C3%A6%C3%A9/" data-title="互斥量" data-description="互斥量"><i data-svg-src="/lib/simple-icons/icons/myspace.min.svg"></i></a><a href="javascript:void(0);" title="分享到 Blogger" data-sharer="blogger" data-url="https://acking-you.gitee.io/posts/%C3%A4%C2%BA%C3%A6%C3%A9/" data-title="互斥量" data-description="互斥量"><i class="fab fa-blogger fa-fw"></i></a><a href="javascript:void(0);" title="分享到 Evernote" data-sharer="evernote" data-url="https://acking-you.gitee.io/posts/%C3%A4%C2%BA%C3%A6%C3%A9/" data-title="互斥量"><i class="fab fa-evernote fa-fw"></i></a></span>
        </div></div><div class="post-nav"><a href="/posts/%C3%A5%C3%A7%C2%BA%C3%A7%C3%A5%C3%A6api%C3%A8%C3%A8/" class="prev" rel="prev" title="多线程异步API解读"><i class="fas fa-angle-left fa-fw"></i>Previous Post</a>
            <a href="/posts/%C3%A6%C3%A4%C3%A5%C3%A9/" class="next" rel="next" title="条件变量">Next Post<i class="fas fa-angle-right fa-fw"></i></a></div></div>
</div></article></div>
            </main>
            <footer class="footer"><div class="footer-container"><div class="footer-line">由 <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.86.0">Hugo</a> 强力驱动 | 主题 - <a href="https://github.com/khusika/FeelIt" target="_blank" rel="noopener noreffer" title="FeelIt 1.0.1"><i class="fas fa-hand-holding-heart fa-fw"></i> FeelIt</a>
        </div><div class="footer-line" itemscope itemtype="http://schema.org/CreativeWork"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2022</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/"></a></span></div>
</div>
</footer>
        </div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="回到顶部">
                <i class="fas fa-chevron-up fa-fw"></i>
            </a></div><link rel="stylesheet" href="/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/lib/animate/animate.min.css"><link rel="stylesheet" href="/lib/katex/katex.min.css"><link rel="stylesheet" href="/lib/katex/copy-tex.min.css"><script src="/lib/autocomplete/autocomplete.min.js"></script><script src="/lib/lunr/lunr.min.js"></script><script src="/lib/lunr/lunr.stemmer.support.min.js"></script><script src="/lib/lunr/lunr.zh.min.js"></script><script src="/lib/lazysizes/lazysizes.min.js"></script><script src="/lib/clipboard/clipboard.min.js"></script><script src="/lib/sharer/sharer.min.js"></script><script src="/lib/katex/katex.min.js"></script><script src="/lib/katex/auto-render.min.js"></script><script src="/lib/katex/copy-tex.min.js"></script><script src="/lib/katex/mhchem.min.js"></script><script>window.config={"code":{"copyTitle":"复制到剪贴板","maxShownLines":200},"comment":{},"math":{"delimiters":[{"display":true,"left":"$$","right":"$$"},{"display":true,"left":"\\[","right":"\\]"},{"display":false,"left":"$","right":"$"},{"display":false,"left":"\\(","right":"\\)"}],"strict":false},"search":{"highlightTag":"em","lunrIndexURL":"/index.json","lunrLanguageCode":"zh","lunrSegmentitURL":"/lib/lunr/lunr.segmentit.js","maxResultLength":100,"noResultsFound":"没有找到结果","snippetLength":50,"type":"lunr"}};</script><script src="/js/theme.min.js"></script></body></html>
